package com.neo.tiny.admin.controller.auth;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.neo.tiny.admin.dto.user.UserInfoDTO;
import com.neo.tiny.admin.params.auth.UserProfilePasswordUpdateReq;
import com.neo.tiny.admin.service.sys.impl.SysAuthService;
import com.neo.tiny.admin.vo.user.UserInfoVO;
import com.neo.tiny.common.common.ResResult;
import com.neo.tiny.secrity.model.AdminUserDetails;
import com.neo.tiny.secrity.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @author yqz
 * @Description 用户信息
 * @CreateDate 2023/6/6 9:18
 */
@Slf4j
@Api(tags = "用户信息")
@RestController
@RequestMapping("/profile")
public class UserProfileController {


    @Autowired
    private SysAuthService authService;

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public ResResult<UserInfoVO> info() {
        AdminUserDetails userDetails = SecurityUtils.getUser();
        log.info("用户信息：{}", userDetails);

        UserInfoVO vo = new UserInfoVO();
        UserInfoDTO dto = BeanUtil.copyProperties(userDetails.getSysUser(), UserInfoDTO.class);

        vo.setSysUser(dto);
        if (CollUtil.isNotEmpty(userDetails.getAuthorities())) {
            vo.setPermissions(userDetails.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority).collect(Collectors.toList()));
        }
        vo.setRoleList(userDetails.getRoleList());
        vo.setPostList(userDetails.getPostList());
        vo.setDept(userDetails.getDept());
        return ResResult.success(vo);
    }


    @ApiOperation("修改用户个人密码")
    @PostMapping("/update-password")
    public ResResult<String> updatePassword(@Valid @RequestBody UserProfilePasswordUpdateReq req) {
        authService.updateUserPassword(SecurityUtils.getUserId(), req);
        return ResResult.success("修改成功");
    }
}
